import { createRouter, createWebHistory } from 'vue-router'
import { getToken } from '@/utils/auth'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'

// 路由配置
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/LoginPage.vue'),
      meta: { title: '登录', requiresAuth: false }
    },
    {
      path: '/home',
      component: () => import('@/views/home/homePage.vue'),
      meta: { title: '首页', requiresAuth: true },
      children: [
        {
          path: '',
          component: () => import('@/views/home/WelcomePage.vue'),
          meta: {
            title: '欢迎',
            requiresAuth: true
          }
        },
        {
          path: 'statistics/data',
          component: () => import('@/views/statistics/statistics.vue'),
          meta: {
            title: '数据统计',
            requiresAuth: true,
            permission: 'statistics:data'
          }
        },
        {
          path: 'user/list',
          component: () => import('@/views/user/UserManage.vue'),
          meta: {
            title: '用户列表',
            requiresAuth: true,
            permission: 'user:list'
          }
        },
        {
          path: 'user/role',
          component: () => import('@/views/user/roleManage.vue'),
          meta: {
            title: '角色管理',
            requiresAuth: true,
            permission: 'user:role'
          }
        },
        {
          path: 'user/permission',
          component: () => import('@/views/user/permission.vue'),
          meta: {
            title: '权限管理',
            requiresAuth: true,
            permission: 'user:permission'
          }
        },
        // 报销管理
        {
          path: 'reimbursement/list',
          component: () => import('@/views/reimbursement/List.vue'),
          meta: {
            title: '报销记录',
            requiresAuth: true,
            permission: 'reimbursement:list'
          }
        },
        {
          path: 'reimbursement/policy',
          component: () => import('@/views/reimbursement/Policy.vue'),
          meta: {
            title: '报销政策',
            requiresAuth: true,
            permission: 'reimbursement:policy'
          }
        },
        // 医院管理
        {
          path: 'hospital/list',
          component: () => import('@/views/hospital/hospital.vue'),
          meta: {
            title: '医院管理',
            requiresAuth: true,
            permission: 'hospital:list'
          }
        },
        // 病人管理
        {
          path: 'patient/list',
          component: () => import('@/views/patient/List.vue'),
          meta: {
            title: '患者列表',
            requiresAuth: true,
            permission: 'patient:list'
          }
        },
        {
          path: 'patient/register',
          component: () => import('@/views/patient/register.vue'),
          meta: {
            title: '参合登记',
            requiresAuth: true,
            permission: 'patient:register'
          }
        },
        // 区域管理
        {
          path: 'region/list',
          component: () => import('@/views/region/regionManage.vue'),
          meta: {
            title: '区域管理',
            requiresAuth: true,
            permission: 'region:list'
          }
        },
        // 疾病管理
        {
          path: 'disease/list',
          component: () => import('@/views/disease/DiseaseManage.vue'),
          meta: {
            title: '疾病列表',
            requiresAuth: true,
            permission: 'disease:list'
          }
        },
        {
          path: 'disease/category',
          component: () => import('@/views/disease/ChronicDiseaseType.vue'),
          meta: {
            title: '慢性病类型',
            requiresAuth: true,
            permission: 'disease:category'
          }
        }
      ]
    },
    {
      path: '/404',
      name: '404',
      component: () => import('@/views/error/NotFound.vue'),
      meta: { title: '404', requiresAuth: false }
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/404'
    }
  ]
})

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  document.title = to.meta.title || '慢性病管理系统'

  const token = getToken()
  const userStore = useUserStore()

  // 登录页无需权限
  if (to.path === '/login') {
    next()
    return
  }

  // 没有token，跳转到登录页
  if (!token) {
    ElMessage.warning('请先登录')
    next({ name: 'login', query: { redirect: to.fullPath } })
    return
  }

  // 尝试从localStorage恢复权限
  if (
    (!userStore.permissions || userStore.permissions.length === 0) &&
    !userStore._permissionsRestoring
  ) {
    userStore._permissionsRestoring = true
    userStore._permissionsRestoring = false
  }

  // 有token但没有权限，尝试加载权限
  if (token && (!userStore.permissions || userStore.permissions.length === 0)) {
    try {
      // 如果没有userId，先从本地存储获取
      if (!userStore.userId) {
        const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}')
        if (userInfo.id) {
          userStore.userId = userInfo.id
        } else {
          ElMessage.error('登录信息已失效，请重新登录')
          next({ name: 'login', query: { redirect: to.fullPath } })
          return
        }
      }

      await userStore.getPermissions()
      next()
    } catch (error) {
      ElMessage.error('获取用户权限失败，请重新登录')
      next({ name: 'login', query: { redirect: to.fullPath } })
    }
    return
  }

  // 检查是否有访问该路由的权限
  const permission = to.meta.permission
  const permissions = userStore.permissions || []

  if (
    permission &&
    !permissions.includes(permission) &&
    !permissions.includes('*:*:*')
  ) {
    ElMessage.error('没有访问权限')
    next({ path: '/home' })
    return
  }

  next()
})

export default router
